<template>
  <div class="cs-view">
    <!-- 左侧边栏 -->
    <div class="sidebar">
      <!-- 客服信息 -->
      <div class="sidebar-header">
        <h3>客服工作台</h3>
        <div v-if="chatStore.currentUser" class="cs-info">
          客服: {{ chatStore.currentUser.username }}
        </div>
      </div>
      
      <!-- 历史会话列表 -->
      <div class="history-list">
        <h3>历史会话</h3>
        <div class="history-content">
          <div 
            v-for="chat in chatHistory" 
            :key="chat.id"
            class="history-item"
            :class="{ 'active': currentChatId === chat.id }"
            @click="handleHistoryClick(chat)"
          >
            <div class="history-title">{{ chat.title || `用户 ${chat.id} 的咨询` }}</div>
            <div class="history-time">{{ formatDate(chat.updatedAt) }}</div>
          </div>
          <div v-if="chatHistory.length === 0" class="no-history">
            暂无历史会话
          </div>
        </div>
      </div>
      
      <!-- 在线用户列表 -->
      <div class="online-users">
        <h3>在线用户</h3>
        <div class="online-content">
          <user-list 
            :users="chatStore.contacts" 
            @select-user="handleUserSelect"
          />
        </div>
      </div>
    </div>
    
    <!-- 右侧聊天区域 -->
    <div class="chat-area">
      <!-- 聊天头部 -->
      <div class="chat-header">
        <div class="chat-header-info">
          <h3>{{ currentChatTitle }}</h3>
          <span v-if="chatStore.currentContact" class="online-status">在线</span>
        </div>
        <div v-if="isAdmin && chatStore.currentContact" class="chat-header-actions">
          <button class="assign-btn" @click="showAssignmentModal = true">
            <i class="fas fa-user-plus"></i>
            分配客服
          </button>
        </div>
      </div>
      
      <!-- 消息列表 -->
      <div class="chat-messages" ref="messagesContainer">
        <div v-if="!chatStore.currentContact" class="no-contact">
          请选择一个用户开始聊天
        </div>
        <template v-else>
          <div 
            v-for="(message, index) in chatStore.currentChatMessages" 
            :key="index"
            :class="['message', message.role === 'assistant' ? 'sent' : message.fromUserId === chatStore.currentUser?.id ? 'sent' : 'received']"
          >
            <div class="message-content">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.createdAt) }}</div>
          </div>
          <div v-if="chatStore.currentChatMessages.length === 0" class="no-messages">
            暂无消息记录
          </div>
        </template>
      </div>
      
      <!-- 消息输入框 -->
      <div class="chat-input">
        <div class="input-wrapper">
          <button class="emoji-btn" @click="toggleEmojiPicker">
            <i class="fas fa-smile"></i>
          </button>
          <input 
            v-model="messageText" 
            type="text" 
            placeholder="请输入消息..." 
            @keyup.enter="handleSendMessage"
            :disabled="!chatStore.currentContact"
          />
        </div>
        <button @click="handleSendMessage" :disabled="!chatStore.currentContact">发送</button>
        
        <!-- 表情选择器 -->
        <div v-if="showEmojiPicker" class="emoji-picker">
          <div class="emoji-categories">
            <button 
              v-for="category in emojiCategories" 
              :key="category.name"
              :class="['category-btn', { active: currentCategory === category.name }]"
              @click="currentCategory = category.name"
            >
              {{ category.icon }}
            </button>
          </div>
          <div class="emoji-list">
            <span 
              v-for="emoji in currentEmojis" 
              :key="emoji"
              class="emoji-item"
              @click="selectEmoji(emoji)"
            >
              {{ emoji }}
            </span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 客服分配弹窗 -->
    <div v-if="showAssignmentModal" class="assignment-modal">
      <div class="assignment-content">
        <div class="assignment-header">
          <h3>分配客服</h3>
          <button class="close-btn" @click="showAssignmentModal = false">×</button>
        </div>
        <div class="assignment-body">
          <customer-service-assignment 
            :userId="chatStore.currentContact?.id"
            :isAdmin="isAdmin"
            @assigned="handleAssigned"
          />
        </div>
        <div class="assignment-footer">
          <button class="cancel-btn" @click="showAssignmentModal = false">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed, nextTick, watch } from 'vue';
import { useChatStore } from '../store/chat';
import CustomerServiceAssignment from '../components/CustomerServiceAssignment.vue';
import UserList from '../components/UserList.vue';
import axios from 'axios';
import { useWebSocket } from '../utils/websocket';

export default {
  components: {
    CustomerServiceAssignment,
    UserList
  },
  setup() {
    const chatStore = useChatStore();
    const messagesContainer = ref(null);
    const showAssignmentModal = ref(false);
    const isAdmin = ref(false);
    const messageText = ref('');
    const chatHistory = ref([]);
    const currentChatId = ref(null);
    const showEmojiPicker = ref(false);
    const currentCategory = ref('smileys');
    
    const { initWebSocket, sendMessage: wsSendMessage, startInactivityTimer, resetInactivityTimer } = useWebSocket();

    // 计算属性
    const currentChatTitle = computed(() => {
      if (!chatStore.currentContact) return '请选择用户';
      return chatStore.currentContact.username;
    });

    // 表情分类
    const emojiCategories = [
      { name: 'smileys', icon: '😊' },
      { name: 'people', icon: '👋' },
      { name: 'animals', icon: '🐶' },
      { name: 'food', icon: '🍎' },
      { name: 'activities', icon: '⚽' },
      { name: 'travel', icon: '✈️' },
      { name: 'objects', icon: '💡' },
      { name: 'symbols', icon: '❤️' },
      { name: 'flags', icon: '🏳️' }
    ];
    
    // 表情数据
    const emojiData = {
      smileys: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳'],
      people: ['👋', '🤚', '🖐️', '✋', '🖖', '👌', '🤌', '🤏', '✌️', '🤞', '🤟', '🤘', '🤙', '👈', '👉', '👆', '🖕', '👇', '☝️', '👍', '👎', '✊', '👊', '🤛', '🤜', '👏', '🙌', '👐', '🤲', '🤝', '🙏'],
      animals: ['🐶', '🐱', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼', '🐨', '🐯', '🦁', '🐮', '🐷', '🐸', '🐵', '🐔', '🐧', '🐦', '🐤', '🦆', '🦅', '🦉', '🦇', '🐺', '🐗', '🐴', '🦄', '🐝', '🐛', '🦋'],
      food: ['🍎', '🍐', '🍊', '🍋', '🍌', '🍉', '🍇', '🍓', '🫐', '🍈', '🍒', '🍑', '🥭', '🍍', '🥥', '🥝', '🍅', '🍆', '🥑', '🥦', '🥬', '🥒', '🌶️', '🫑', '🌽', '🥕', '🫒', '🧄', '🧅', '🥔'],
      activities: ['⚽', '🏀', '🏈', '⚾', '🥎', '🎾', '🏐', '🏉', '🎱', '🏓', '🏸', '🏒', '🏑', '🥍', '🏏', '🥊', '🥋', '🥅', '⛳', '⛸️', '🎣', '🤿', '🎽', '🛹', '🛷', '⛷️', '🏂', '🏋️', '🤼', '🤸'],
      travel: ['✈️', '🛫', '🛬', '🛩️', '💺', '🛰️', '🚀', '🛸', '🚁', '🛶', '⛵', '🚤', '🛥️', '🛳️', '⛴️', '🚢', '🚗', '🚕', '🚙', '🚘', '🚎', '🏎️', '🚓', '🚑', '🚒', '🚐', '🚚', '🚛', '🚜', '🛴'],
      objects: ['💡', '🔦', '🕯️', '📱', '📲', '💻', '⌨️', '🖥️', '🖨️', '🖱️', '🖲️', '🕹️', '🗜️', '💽', '💾', '💿', '📀', '📼', '📷', '📸', '📹', '🎥', '📽️', '🎞️', '📞', '☎️', '📟', '📠', '📺', '📻'],
      symbols: ['❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '🤎', '💔', '❤️‍🔥', '❤️‍🩹', '💖', '💗', '💓', '💞', '💕', '💟', '❣️', '💝', '💘', '💌', '💋', '💯', '💢', '💥', '💫', '💦', '💨', '🕳️'],
      flags: ['🏳️', '🏴', '🏁', '🚩', '🏳️‍🌈', '🏳️‍⚧️', '🏴‍☠️', '🇦🇫', '🇦🇽', '🇦🇱', '🇩🇿', '🇦🇸', '🇦🇩', '🇦🇴', '🇦🇮', '🇦🇶', '🇦🇬', '🇦🇷', '🇦🇲', '🇦🇼', '🇦🇺', '🇦🇹', '🇦🇿', '🇧🇸', '🇧🇭', '🇧🇩', '🇧🇪', '🇧🇿', '🇧🇯', '🇧🇲']
    };
    
    // 当前分类的表情列表
    const currentEmojis = computed(() => emojiData[currentCategory.value] || []);
    
    // 切换表情选择器
    const toggleEmojiPicker = () => {
      showEmojiPicker.value = !showEmojiPicker.value;
    };
    
    // 选择表情
    const selectEmoji = (emoji) => {
      messageText.value += emoji;
      showEmojiPicker.value = false;
    };
    
    // 点击外部关闭表情选择器
    const handleClickOutside = (event) => {
      const emojiPicker = document.querySelector('.emoji-picker');
      const emojiBtn = document.querySelector('.emoji-btn');
      
      if (emojiPicker && !emojiPicker.contains(event.target) && 
          emojiBtn && !emojiBtn.contains(event.target)) {
        showEmojiPicker.value = false;
      }
    };

    // 处理历史会话点击
    const handleHistoryClick = async (chat) => {
      currentChatId.value = chat.id;
      await loadChat(chat.id);
    };

    // 处理用户选择
    const handleUserSelect = async (contact) => {
      currentChatId.value = contact.id;
      chatStore.setContact(contact);
      
      try {
        // 先尝试从历史记录中加载
        const response = await axios.get(`/api/conversation/history/${contact.id}`, {
          headers: { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' }
        });
        
        if (response.data?.code === '00000') {
          const messages = response.data.data || [];
          const formattedMessages = messages.map(msg => ({
            content: msg.content,
            fromUserId: msg.role === 'user' ? contact.id : chatStore.currentUser?.id,
            toUserId: msg.role === 'user' ? chatStore.currentUser?.id : contact.id,
            createdAt: new Date(msg.createdAt || Date.now()),
            role: msg.role
          }));
          
          chatStore.setCurrentChatMessages(formattedMessages);
          await scrollToBottom();
        } else {
          // 如果历史记录加载失败，尝试加载当前消息
          await loadContactHistory(contact.id);
        }
      } catch (error) {
        console.error('加载历史消息失败:', error);
        // 如果历史记录加载失败，尝试加载当前消息
        await loadContactHistory(contact.id);
      }
    };

    // 监听消息变化，自动滚动到底部
    watch(() => chatStore.currentChatMessages.length, () => {
      nextTick(() => {
        scrollToBottom();
      });
    });

    // 监听当前联系人变化，自动滚动到底部
    watch(() => chatStore.currentContact, () => {
      nextTick(() => {
        scrollToBottom();
      });
    });

    // 滚动到底部
    const scrollToBottom = async () => {
      await nextTick();
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
      }
    };

    // 处理发送消息
    const handleSendMessage = async () => {
      if (!messageText.value.trim() || !chatStore.currentContact) return;
      
      if (!wsSendMessage || typeof wsSendMessage !== 'function') {
        alert('网络连接异常，请刷新页面重试');
        return;
      }
      
      const success = wsSendMessage(messageText.value, chatStore.currentContact.id);
      
      if (success) {
        messageText.value = '';
        resetInactivityTimer();
        await scrollToBottom();
      } else {
        alert('消息发送失败，请检查网络连接');
      }
    };

    // 加载聊天历史
    const loadChatHistory = async () => {
      try {
        if (!chatStore.currentUser?.id) return;
        
        const response = await axios.get('/api/conversation/list/history', {
          headers: { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' }
        });
        
        if (response.data?.code === '00000') {
          const userIds = response.data.data || [];
          chatHistory.value = userIds.map(userId => ({
            id: userId,
            title: `用户 ${userId} 的咨询`,
            updatedAt: new Date(),
            contactId: userId
          }));
          
          if (chatHistory.value.length > 0) {
            await loadChat(chatHistory.value[0].id);
          }
        }
      } catch (error) {
        console.error('加载聊天历史失败:', error);
        chatHistory.value = [];
      }
    };

    // 加载特定对话
    const loadChat = async (chatId) => {
      try {
        const response = await axios.get(`/api/conversation/history/${chatId}`, {
          headers: { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' }
        });
        
        if (response.data?.code === '00000') {
          const messages = response.data.data || [];
          console.log('加载到的历史消息:', messages); // 添加日志
          
          // 将消息按时间顺序排序（从旧到新）
          const formattedMessages = messages.map((msg, index) => {
            const message = {
              content: msg.content,
              fromUserId: msg.role === 'user' ? chatId : chatStore.currentUser?.id,
              toUserId: msg.role === 'user' ? chatStore.currentUser?.id : chatId,
              createdAt: new Date(Date.now() - (messages.length - index) * 1000), // 模拟时间顺序
              role: msg.role
            };
            console.log('格式化后的消息:', message); // 添加日志
            return message;
          });
          
          console.log('所有格式化后的消息:', formattedMessages); // 添加日志
          
          // 设置当前联系人
          const contact = chatStore.contacts.find(c => String(c.id) === String(chatId)) || {
            id: Number(chatId),
            username: `用户 ${chatId}`
          };
          chatStore.setContact(contact);
          
          // 设置消息
          chatStore.setCurrentChatMessages(formattedMessages);
          console.log('设置后的消息:', chatStore.currentChatMessages); // 添加日志

          // 更新历史会话列表
          const historyItem = chatHistory.value.find(item => item.id === chatId);
          if (historyItem) {
            historyItem.updatedAt = new Date();
            // 将当前会话移到列表顶部
            chatHistory.value = [
              historyItem,
              ...chatHistory.value.filter(item => item.id !== chatId)
            ];
          } else {
            // 如果历史会话中不存在，则添加新的历史会话
            chatHistory.value.unshift({
              id: chatId,
              title: `用户 ${chatId} 的咨询`,
              updatedAt: new Date(),
              contactId: chatId
            });
          }
          
          // 滚动到底部
          await scrollToBottom();
        }
      } catch (error) {
        console.error('加载对话消息失败:', error);
      }
    };

    // 加载联系人历史消息
    const loadContactHistory = async (contactId) => {
      try {
        const response = await axios.get(`/api/chat/cs/contact-messages/${contactId}`);
        
        if (response.data?.code === 200) {
          const messages = response.data.data || [];
          const formattedMessages = messages.map(msg => ({
            content: msg.content,
            fromUserId: msg.role === 'user' ? contactId : chatStore.currentUser?.id,
            toUserId: msg.role === 'user' ? chatStore.currentUser?.id : contactId,
            createdAt: new Date(),
            role: msg.role
          }));
          
          chatStore.setCurrentChatMessages(formattedMessages);
          await scrollToBottom();
        }
      } catch (error) {
        console.error('加载联系人消息失败:', error);
      }
    };

    // 检查管理员权限
    const checkIsAdmin = async () => {
      try {
        if (!chatStore.currentUser?.id) return;
        
        const response = await axios.get(`/api/chat/cs/roles/${chatStore.currentUser.id}`, {
          headers: { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' }
        });
        
        if (response.data?.code === 200) {
          const roleIds = response.data.data;
          isAdmin.value = Array.isArray(roleIds) && roleIds.includes(1);
        }
      } catch (error) {
        console.error('检查管理员权限失败:', error);
      }
    };

    // 处理客服分配
    const handleAssigned = (customerService) => {
      if (customerService) {
        showAssignmentModal.value = false;
      }
    };

    // 格式化时间
    const formatTime = (timestamp) => {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    };

    // 格式化日期
    const formatDate = (timestamp) => {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    };

    // 初始化
    onMounted(async () => {
      startInactivityTimer();
      await checkIsAdmin();
      
      const userStr = localStorage.getItem('user');
      if (userStr) {
        const user = JSON.parse(userStr);
        chatStore.setCurrentUser(user);
        
        try {
          await initWebSocket(user.username, user.teamId, true);
          await loadChatHistory();
        } catch (error) {
          console.error('初始化失败:', error);
        }
      }
      document.addEventListener('click', handleClickOutside);
    });

    return {
      chatStore,
      messagesContainer,
      showAssignmentModal,
      isAdmin,
      messageText,
      chatHistory,
      currentChatId,
      currentChatTitle,
      handleHistoryClick,
      handleUserSelect,
      handleSendMessage,
      handleAssigned,
      formatTime,
      formatDate,
      showEmojiPicker,
      currentCategory,
      emojiCategories,
      currentEmojis,
      toggleEmojiPicker,
      selectEmoji,
      scrollToBottom
    };
  }
}
</script>

<style scoped>
.cs-view {
  height: 100vh;
  display: flex;
  background-color: #f0f2f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  position: relative;
  overflow: hidden;
}

.sidebar {
  width: 320px;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border-right: 1px solid rgba(0, 0, 0, 0.06);
  position: relative;
  z-index: 1;
  overflow: hidden;
}

.sidebar-header {
  padding: 24px;
  background: linear-gradient(135deg, #1976d2, #2196f3);
  color: white;
  position: relative;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.sidebar-header::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 60%);
  animation: rotate 20s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.sidebar-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  letter-spacing: 0.5px;
  position: relative;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 8px;
}

.cs-info {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  margin-top: 12px;
  padding: 10px 14px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  backdrop-filter: blur(4px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
}

.cs-info::before {
  content: '';
  width: 8px;
  height: 8px;
  background-color: #4caf50;
  border-radius: 50%;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.history-list, .online-users {
  display: flex;
  flex-direction: column;
  height: 0;
  flex: 1;
  overflow: hidden;
  background-color: #ffffff;
  position: relative;
}

.history-list h3, .online-users h3 {
  color: #1a1a1a;
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  padding: 20px 20px 12px;
  border-bottom: 2px solid #f0f2f5;
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
  background-color: #ffffff;
  flex-shrink: 0;
  z-index: 1;
}

.history-list h3::before, .online-users h3::before {
  content: '';
  width: 4px;
  height: 16px;
  background: linear-gradient(to bottom, #1976d2, #2196f3);
  border-radius: 2px;
}

.history-content, .online-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px 20px;
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.2) transparent;
  background-color: #ffffff;
}

.history-item {
  padding: 16px;
  border-radius: 12px;
  cursor: pointer;
  margin-bottom: 12px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background-color: #ffffff;
  border: 1px solid #f0f2f5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  position: relative;
  overflow: hidden;
}

.history-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
  transform: translateX(-100%);
  transition: transform 0.6s;
}

.history-item:hover::before {
  transform: translateX(100%);
}

.history-item:hover {
  background-color: #f8f9fa;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.history-item.active {
  background-color: #e3f2fd;
  border-color: #90caf9;
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.12);
}

.history-item.active::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 3px;
  height: 100%;
  background: linear-gradient(to bottom, #1976d2, #2196f3);
  border-radius: 0 2px 2px 0;
}

.history-title {
  font-weight: 500;
  color: #1a1a1a;
  margin-bottom: 8px;
  font-size: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.history-title::before {
  content: '';
  width: 6px;
  height: 6px;
  background-color: #1976d2;
  border-radius: 50%;
  opacity: 0.6;
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.1);
}

.history-time {
  font-size: 13px;
  color: #8c8c8c;
  display: flex;
  align-items: center;
  gap: 6px;
  padding-left: 14px;
  position: relative;
}

.history-time::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  width: 4px;
  height: 4px;
  background-color: #d9d9d9;
  border-radius: 50%;
  transform: translateY(-50%);
}

.no-history {
  text-align: center;
  padding: 24px;
  color: #8c8c8c;
  font-size: 14px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px dashed #e8e8e8;
  margin-top: 12px;
  position: relative;
}

.no-history::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #f0f2f5, #e6e9ed);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  opacity: 0.5;
  z-index: 0;
}

/* 添加分隔线效果 */
.history-list::after, .online-users::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(to right,
    transparent,
    rgba(0, 0, 0, 0.06) 20%,
    rgba(0, 0, 0, 0.06) 80%,
    transparent
  );
  z-index: 1;
}

/* 优化滚动条样式 */
.history-content::-webkit-scrollbar,
.online-content::-webkit-scrollbar {
  width: 6px;
}

.history-content::-webkit-scrollbar-track,
.online-content::-webkit-scrollbar-track {
  background: transparent;
}

.history-content::-webkit-scrollbar-thumb,
.online-content::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.history-content::-webkit-scrollbar-thumb:hover,
.online-content::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.3);
}

/* 添加内容区域的背景图案 */
.history-content, .online-content {
  background-image: 
    linear-gradient(rgba(0, 0, 0, 0.02) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 0, 0, 0.02) 1px, transparent 1px);
  background-size: 20px 20px;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  box-shadow: -2px 0 12px rgba(0, 0, 0, 0.06);
  position: relative;
}

.chat-header {
  padding: 20px 24px;
  background-color: #ffffff;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.chat-header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(to right,
    transparent,
    rgba(0, 0, 0, 0.06) 20%,
    rgba(0, 0, 0, 0.06) 80%,
    transparent
  );
}

.chat-header-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chat-header-info h3 {
  margin: 0;
  color: #1a1a1a;
  font-size: 18px;
  font-weight: 600;
  position: relative;
}

.online-status {
  font-size: 13px;
  color: #52c41a;
  background-color: #f6ffed;
  padding: 4px 12px;
  border-radius: 12px;
  border: 1px solid #b7eb8f;
  display: flex;
  align-items: center;
  gap: 6px;
}

.online-status::before {
  content: '';
  width: 6px;
  height: 6px;
  background-color: #52c41a;
  border-radius: 50%;
  box-shadow: 0 0 0 2px rgba(82, 196, 26, 0.2);
}

.chat-header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.assign-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background-color: #1976d2;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
}

.assign-btn:hover {
  background-color: #1565c0;
  transform: translateY(-1px);
}

.assign-btn i {
  font-size: 14px;
}

.chat-messages {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background-color: #f5f7fa;
  background-image: 
    linear-gradient(rgba(0, 0, 0, 0.02) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 0, 0, 0.02) 1px, transparent 1px);
  background-size: 20px 20px;
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.2) transparent;
  display: flex;
  flex-direction: column;
}

.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: transparent;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.message {
  margin-bottom: 24px;
  max-width: 70%;
  display: inline-block;
  width: auto;
  clear: both;
  word-break: break-word;
  position: relative;
}

.message.sent {
  margin-left: auto;
  margin-right: 0;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.message.received {
  margin-right: auto;
  margin-left: 0;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.message-content {
  padding: 12px 18px;
  border-radius: 16px;
  word-break: break-word;
  display: inline-block;
  max-width: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  line-height: 1.5;
  font-size: 15px;
  position: relative;
}

.sent .message-content {
  background: linear-gradient(135deg, #1976d2, #2196f3);
  color: white;
  border-top-right-radius: 4px;
}

.sent .message-content::after {
  content: '';
  position: absolute;
  top: 0;
  right: -6px;
  width: 12px;
  height: 12px;
  background: linear-gradient(135deg, #1976d2, #2196f3);
  transform: rotate(45deg);
  z-index: -1;
}

.received .message-content {
  background-color: #ffffff;
  color: #1a1a1a;
  border-top-left-radius: 4px;
  border: 1px solid #f0f2f5;
}

.received .message-content::after {
  content: '';
  position: absolute;
  top: 0;
  left: -6px;
  width: 12px;
  height: 12px;
  background-color: #ffffff;
  border-left: 1px solid #f0f2f5;
  border-bottom: 1px solid #f0f2f5;
  transform: rotate(45deg);
  z-index: -1;
}

.message-time {
  font-size: 12px;
  color: #8c8c8c;
  margin-top: 8px;
  text-align: right;
  display: block;
  position: relative;
  padding-right: 12px;
}

.message-time::after {
  content: '';
  position: absolute;
  right: 0;
  top: 50%;
  width: 4px;
  height: 4px;
  background-color: #d9d9d9;
  border-radius: 50%;
  transform: translateY(-50%);
}

.chat-input {
  padding: 20px 24px;
  background-color: #ffffff;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
  display: flex;
  gap: 12px;
  position: relative;
}

.chat-input::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(to right,
    transparent,
    rgba(0, 0, 0, 0.06) 20%,
    rgba(0, 0, 0, 0.06) 80%,
    transparent
  );
}

.input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #f5f7fa;
  border: 1px solid #f0f2f5;
  border-radius: 8px;
  padding: 0 12px;
  transition: all 0.3s ease;
}

.input-wrapper:focus-within {
  background-color: #ffffff;
  border-color: #1976d2;
  box-shadow: 0 0 0 3px rgba(25, 118, 210, 0.1);
}

.emoji-btn {
  background: none;
  border: none;
  padding: 8px;
  cursor: pointer;
  color: #666;
  transition: all 0.3s ease;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.emoji-btn:hover {
  background-color: rgba(0, 0, 0, 0.05);
  color: #1976d2;
}

.chat-input input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #f0f2f5;
  border-radius: 8px;
  font-size: 15px;
  transition: all 0.3s ease;
  background-color: #f5f7fa;
}

.chat-input input:focus {
  outline: none;
  border-color: #1976d2;
  background-color: #ffffff;
  box-shadow: 0 0 0 3px rgba(25, 118, 210, 0.1);
}

.chat-input button {
  padding: 12px 24px;
  background: linear-gradient(135deg, #1976d2, #2196f3);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  font-size: 15px;
  position: relative;
  overflow: hidden;
}

.chat-input button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(255, 255, 255, 0.2),
    transparent
  );
  transition: 0.5s;
}

.chat-input button:hover::before {
  left: 100%;
}

.chat-input button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.2);
}

.chat-input button:disabled {
  background: #e0e0e0;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.no-contact, .no-messages {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #8c8c8c;
  font-size: 16px;
  background-color: #f5f7fa;
  position: relative;
}

.no-contact::before, .no-messages::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #f0f2f5, #e6e9ed);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  opacity: 0.5;
  z-index: 0;
}

.assignment-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.assignment-content {
  background-color: white;
  border-radius: 16px;
  width: 500px;
  max-width: 90%;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  animation: modalSlideIn 0.3s ease;
  position: relative;
  overflow: hidden;
}

.assignment-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(to right, #1976d2, #2196f3);
}

@keyframes modalSlideIn {
  from {
    transform: translateY(20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.assignment-header {
  padding: 20px 24px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.assignment-header h3 {
  margin: 0;
  font-size: 18px;
  color: #1a1a1a;
  font-weight: 600;
  position: relative;
  padding-left: 12px;
}

.assignment-header h3::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  width: 4px;
  height: 16px;
  background: linear-gradient(to bottom, #1976d2, #2196f3);
  border-radius: 2px;
  transform: translateY(-50%);
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #8c8c8c;
  transition: all 0.3s ease;
  padding: 4px;
  line-height: 1;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.close-btn::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  border-radius: 50%;
  transform: translate(-50%, -50%) scale(0);
  transition: transform 0.3s ease;
}

.close-btn:hover::before {
  transform: translate(-50%, -50%) scale(1);
}

.close-btn:hover {
  color: #1a1a1a;
}

.assignment-body {
  padding: 24px;
  overflow-y: auto;
  flex: 1;
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.2) transparent;
}

.assignment-body::-webkit-scrollbar {
  width: 6px;
}

.assignment-body::-webkit-scrollbar-track {
  background: transparent;
}

.assignment-body::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.assignment-footer {
  padding: 20px 24px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  position: relative;
}

.assignment-footer::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(to right,
    transparent,
    rgba(0, 0, 0, 0.06) 20%,
    rgba(0, 0, 0, 0.06) 80%,
    transparent
  );
}

.cancel-btn {
  background-color: #f5f7fa;
  color: #1a1a1a;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  font-size: 15px;
  position: relative;
  overflow: hidden;
}

.cancel-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(0, 0, 0, 0.05),
    transparent
  );
  transition: 0.5s;
}

.cancel-btn:hover::before {
  left: 100%;
}

.cancel-btn:hover {
  background-color: #e8e8e8;
  transform: translateY(-1px);
}

.emoji-picker {
  position: absolute;
  bottom: 100%;
  left: 0;
  width: 320px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  margin-bottom: 12px;
  overflow: hidden;
  z-index: 1000;
}

.emoji-categories {
  display: flex;
  padding: 8px;
  border-bottom: 1px solid #f0f2f5;
  background-color: #f8f9fa;
}

.category-btn {
  background: none;
  border: none;
  padding: 8px;
  cursor: pointer;
  font-size: 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.category-btn:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.category-btn.active {
  background-color: #e3f2fd;
  color: #1976d2;
}

.emoji-list {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 4px;
  padding: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.emoji-item {
  font-size: 24px;
  padding: 8px;
  cursor: pointer;
  text-align: center;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.emoji-item:hover {
  background-color: #f0f2f5;
  transform: scale(1.1);
}
</style>
